var app = getApp()
Page({
  data: {
    ableAddFriend: false,
    show: false,
    download: {
      _openid: '',
      nickName: '',
      avatarUrl: '', //头像
      cloud_imageID: [], //展现页面的data还需要存临时链接
      tempImageUrl: [],
      title: '',
      publish_time: "",
      time: '',
      noName: false,//匿名
      rate: [],
      formId: ""
    }
  },
  onLoad() {

  },
  onReady() {
    this.setData({
      show: true
    })
  },
  onUnload() {
    //console.log("sd")
  },
  inputTitle(e) {
    // //console.log(e)
    this.setData({
      'download.title': e.detail.value
    })
  },
  switch(e) {
    //console.log(e)
    this.setData({
      'download.noName': e.detail.value
    })
  },

  doSubmit(e) {
    //console.log(app.globalData.userInfo.nickName)
    var time = new Date()
    this.setData({
      'download.nickName': app.globalData.userInfo.nickName,
      'download.avatarUrl': app.globalData.userInfo.avatarUrl,
      'download._openid': app.globalData.openid,
      'download.formId': e.detail.formId,
      'download.publish_time': new Date().getTime(),
      'download.time': time.getFullYear() + '年' + (time.getMonth() + 1) + "月" + time.getDate() + "日",
    })
    if (this.data.download.tempImageUrl.length < 1) {
      qq.showToast({
        icon: "none",
        title: "您还没有上传图片哦～"
      })
    }
    else if (this.data.download.title.length < 2) {
      qq.showToast({
        icon: "none",
        title: "标题不能小于两个字哦~"
      })
    } else {
      this.uploadFile()
    }
  },
  uploadFile() {
    var i = 0 //正在上传第i
    var j = 0 //已经上传j
    var that = this
    var num = that.data.download.tempImageUrl.length
    qq.showLoading({
      title: '上传' + i + '/' + num
    })
    var s = setInterval(function () {
      //console.log(i, j, num)
      if (j == num) {
        that.addToDB()
        clearInterval(s)
      } else if (j == i) {
        qq.hideLoading()
        qq.showLoading({
          title: '上传' + i + '/' + num
        })
        i++;//此时i>j
        //下面进行上传图片，完成第i张上传后，j++，此时j=i
        const filePath = that.data.download.tempImageUrl[i - 1]//第一张为0
        const cloudPath = 'download/' + app.globalData.openid + new Date().getTime() + filePath.match(/\.[^.]+?$/)[0]
        var url = 'https://api.weixin.qq.com/tcb/uploadfile?access_token=' + app.globalData.access_token
        //console.log(url)
        qq.request({////////////////////////获取cos的url
          url,
          header: {
            'content-type': 'application/json' // 默认值
          },
          data: {
            "env": app.globalData.myEnv,
            "path": cloudPath
          },
          method: "POST",
          success(res1) {//////////////////////////通过cos上传
            //console.log(1, res1)
            qq.uploadFile({
              url: res1.data.url,
              filePath,
              name: 'file',
              header: {
                "Content-Type": "multipart/form-data"//记得设置
              },
              formData: {
                key: cloudPath,
                "Signature": res1.data.authorization,
                "x-cos-security-token": res1.data.token,
                "x-cos-meta-fileid": res1.data.cos_file_id
              },
              success(res2) { ////////////////////添加到数据库
                that.setData({
                  'download.cloud_imageID': that.data.download.cloud_imageID.concat(res1.data.file_id)
                })
                j++
                //console.log(res2)
              }, fail(msg) {
                //console.log(msg)
              }
            })
            //console.log(res1)
          }
        })
      }
    }, 10)
  },
  addToDB() {
    var data = JSON.stringify(this.data.download)
    qq.request({
      url: 'https://api.weixin.qq.com/tcb/databaseadd?access_token=' + app.globalData.access_token, // 仅为示例，并非真实的接口地址
      header: {
        'content-type': 'application/json' // 默认值
      }, method: "post",
      data: {
        "env": app.globalData.myEnv,
        "query": "db.collection(\"download\").add({\
            data: "+ data + "\
        })"
      },
      success(res) {
        qq.hideLoading()
        qq.showToast({
          title: "上传成功"
        })
        qq.navigateBack()
        //console.log(res.data)
      }
    })
  },



  ChooseImage() {
    wx.chooseImage({ ////一次选择多张需要一张上传完毕后在上传
      count: 9, //默认9
      sizeType: ['original'], //可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'],
      success: (res) => {
        //console.log(res)
        this.zipImg(0,res.tempFilePaths)
      }
    });
  },
  zipImg(index, tempFilePaths) {
    var that = this
    if (index < tempFilePaths.length) {/////对每一个进行循环，获取连接后写入data
      qq.getImageInfo({
        src: tempFilePaths[index],
        success(res) {
          //console.log(res)
          var targetHeight = res.height
          var targetWidth = res.width
          var maxWidth = 600
          var maxHeight = 1200 //2100以内 按宽度1000，高度自适应压缩，
          //console.log(targetHeight, targetWidth)

          if (targetWidth > maxWidth || targetHeight > maxHeight) {
            if ((targetWidth / targetHeight) > (maxWidth / maxHeight)) {
              targetHeight = Math.round(maxWidth * (targetHeight / targetWidth));
              targetWidth = maxWidth;
              // //console.log(">") 顺序什么都不能改变，易错
            } else {
              targetWidth = Math.round(maxHeight * (targetWidth / targetHeight));
              targetHeight = maxHeight;
            }
          }
          //console.log(targetHeight, targetWidth)

          that.setData({
            targetWidth: targetWidth,
            targetHeight: targetHeight,
            canvasShow: true
          })
          setTimeout(function () {
            const ctx = qq.createCanvasContext('canvas');
            ctx.drawImage(tempFilePaths[index], 0, 0, targetWidth, targetHeight);
            ctx.draw(false, function () {
              qq.canvasToTempFilePath({
                canvasId: ('canvas'),
                fileType: "jpg",
                quality: 0.6,
                // destWidth: targetWidth,
                // destHeight: targetHeight,
                success(res) {
                  that.setData({
                    'download.tempImageUrl': that.data.download.tempImageUrl.concat(res.tempFilePath),
                    canvasShow: false
                  })
                  setTimeout(function () {
                    index++
                    that.zipImg(index, tempFilePaths);
                    //console.log(res)
                  }, 100)
                }
              })
            })
          }, 100)

        }
      })
    }
  },
  ViewImage(e) {
    wx.previewImage({
      urls: this.data.download.tempImageUrl,
      current: e.currentTarget.dataset.url
    });
  },
  DelImg(e) {
    this.data.download.tempImageUrl.splice(e.currentTarget.dataset.index, 1);
    this.setData({
      'download.tempImageUrl': this.data.download.tempImageUrl
    })
  },
})